<template>
  <div class="loan-record">
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" inline>
        <el-form-item label="贷款编号" prop="loanNo">
          <el-input
            v-model="searchForm.loanNo"
            placeholder="请输入贷款编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="客户姓名" prop="customerName">
          <el-input
            v-model="searchForm.customerName"
            placeholder="请输入客户姓名"
            clearable
          />
        </el-form-item>
        <el-form-item label="贷款类型" prop="loanType">
          <el-select
            v-model="searchForm.loanType"
            placeholder="请选择贷款类型"
            clearable
            style="width: 120px"
          >
            <el-option label="个人消费贷" value="personal" />
            <el-option label="住房贷款" value="house" />
            <el-option label="车辆贷款" value="car" />
            <el-option label="经营贷款" value="business" />
          </el-select>
        </el-form-item>
        <el-form-item label="贷款状态" prop="status">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="已放款" value="disbursed" />
            <el-option label="已结清" value="closed" />
            <el-option label="已逾期" value="overdue" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 贷款记录列表 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="loanNo" label="贷款编号" width="180" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="loanType" label="贷款类型" width="120">
          <template #default="scope">
            {{ getLoanTypeText(scope.row.loanType) }}
          </template>
        </el-table-column>
        <el-table-column prop="loanAmount" label="贷款金额" width="120">
          <template #default="scope">
            {{ formatMoney(scope.row.loanAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="paidAmount" label="已还金额" width="120">
          <template #default="scope">
            {{ formatMoney(scope.row.paidAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="remainAmount" label="剩余金额" width="120">
          <template #default="scope">
            {{ formatMoney(scope.row.remainAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="paidPeriods" label="已还期数" width="100">
          <template #default="scope">
            {{ scope.row.paidPeriods }}/{{ scope.row.totalPeriods }}
          </template>
        </el-table-column>
        <el-table-column prop="nextPaymentDate" label="下次还款日" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="放款时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleDetail(scope.row)"
            >
              详情
            </el-button>
            <el-button
              v-if="scope.row.status === 'disbursed'"
              link
              type="success"
              @click="handleRepayment(scope.row)"
            >
              还款
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="贷款详情"
      width="800px"
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="贷款编号">{{ detail.loanNo }}</el-descriptions-item>
        <el-descriptions-item label="客户姓名">{{ detail.customerName }}</el-descriptions-item>
        <el-descriptions-item label="贷款类型">{{ getLoanTypeText(detail.loanType) }}</el-descriptions-item>
        <el-descriptions-item label="贷款金额">{{ formatMoney(detail.loanAmount) }}</el-descriptions-item>
        <el-descriptions-item label="已还金额">{{ formatMoney(detail.paidAmount) }}</el-descriptions-item>
        <el-descriptions-item label="剩余金额">{{ formatMoney(detail.remainAmount) }}</el-descriptions-item>
        <el-descriptions-item label="贷款期限">{{ detail.totalPeriods }}个月</el-descriptions-item>
        <el-descriptions-item label="已还期数">{{ detail.paidPeriods }}期</el-descriptions-item>
        <el-descriptions-item label="年利率">{{ detail.interestRate }}%</el-descriptions-item>
        <el-descriptions-item label="还款方式">{{ getRepaymentMethodText(detail.repaymentMethod) }}</el-descriptions-item>
        <el-descriptions-item label="月供">{{ formatMoney(detail.monthlyPayment) }}</el-descriptions-item>
        <el-descriptions-item label="下次还款日">{{ detail.nextPaymentDate }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(detail.status)">
            {{ getStatusText(detail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="放款时间">{{ detail.createTime }}</el-descriptions-item>
      </el-descriptions>

      <!-- 还款计划 -->
      <div class="repayment-plan">
        <div class="title">还款计划</div>
        <el-table :data="detail.repaymentPlan" border stripe>
          <el-table-column type="index" label="期数" width="80" align="center" />
          <el-table-column prop="dueDate" label="应还日期" width="120" />
          <el-table-column prop="totalAmount" label="应还金额" width="120">
            <template #default="scope">
              {{ formatMoney(scope.row.totalAmount) }}
            </template>
          </el-table-column>
          <el-table-column prop="principal" label="应还本金" width="120">
            <template #default="scope">
              {{ formatMoney(scope.row.principal) }}
            </template>
          </el-table-column>
          <el-table-column prop="interest" label="应还利息" width="120">
            <template #default="scope">
              {{ formatMoney(scope.row.interest) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getRepaymentStatusType(scope.row.status)">
                {{ getRepaymentStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="paymentTime" label="实还时间" />
        </el-table>
      </div>
    </el-dialog>

    <!-- 还款弹窗 -->
    <el-dialog
      v-model="repaymentVisible"
      title="贷款还款"
      width="600px"
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="贷款编号">{{ currentLoan.loanNo }}</el-descriptions-item>
        <el-descriptions-item label="客户姓名">{{ currentLoan.customerName }}</el-descriptions-item>
        <el-descriptions-item label="贷款金额">{{ formatMoney(currentLoan.loanAmount) }}</el-descriptions-item>
        <el-descriptions-item label="月供">{{ formatMoney(currentLoan.monthlyPayment) }}</el-descriptions-item>
        <el-descriptions-item label="已还期数">{{ currentLoan.paidPeriods }}期</el-descriptions-item>
        <el-descriptions-item label="剩余期数">{{ currentLoan.totalPeriods - currentLoan.paidPeriods }}期</el-descriptions-item>
      </el-descriptions>

      <el-form
        ref="repaymentFormRef"
        :model="repaymentForm"
        :rules="repaymentRules"
        label-width="100px"
        style="margin-top: 20px"
      >
        <el-form-item label="还款金额" prop="amount">
          <el-input-number
            v-model="repaymentForm.amount"
            :min="0"
            :precision="2"
            :step="100"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="还款方式" prop="method">
          <el-select v-model="repaymentForm.method" style="width: 100%">
            <el-option label="银行转账" value="bank" />
            <el-option label="现金" value="cash" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="repaymentForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="repaymentVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRepaymentSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索表单
const searchForm = reactive({
  loanNo: '',
  customerName: '',
  loanType: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)
const tableData = ref([
  {
    loanNo: 'L202403010001',
    customerName: '张三',
    loanType: 'personal',
    loanAmount: 100000,
    paidAmount: 25749.99,
    remainAmount: 74250.01,
    totalPeriods: 12,
    paidPeriods: 3,
    interestRate: 4.35,
    monthlyPayment: 8583.33,
    repaymentMethod: 'equal',
    nextPaymentDate: '2024-06-01',
    status: 'disbursed',
    createTime: '2024-03-01 10:00:00'
  }
])

// 详情数据
const detailVisible = ref(false)
const detail = ref({
  repaymentPlan: [
    {
      dueDate: '2024-04-01',
      totalAmount: 8583.33,
      principal: 8000,
      interest: 583.33,
      status: 'paid',
      paymentTime: '2024-04-01 10:00:00'
    },
    {
      dueDate: '2024-05-01',
      totalAmount: 8583.33,
      principal: 8100,
      interest: 483.33,
      status: 'paid',
      paymentTime: '2024-05-01 10:00:00'
    },
    {
      dueDate: '2024-06-01',
      totalAmount: 8583.33,
      principal: 8200,
      interest: 383.33,
      status: 'pending'
    }
  ]
})

// 还款数据
const repaymentVisible = ref(false)
const repaymentFormRef = ref(null)
const currentLoan = ref({})
const repaymentForm = reactive({
  amount: 0,
  method: 'bank',
  remark: ''
})

const repaymentRules = {
  amount: [
    { required: true, message: '请输入还款金额', trigger: 'blur' }
  ],
  method: [
    { required: true, message: '请选择还款方式', trigger: 'change' }
  ]
}

// 查询
const handleSearch = () => {
  loading.value = true
  // TODO: 实现查询逻辑
  setTimeout(() => {
    loading.value = false
  }, 500)
}

// 重置
const handleReset = () => {
  searchForm.loanNo = ''
  searchForm.customerName = ''
  searchForm.loanType = ''
  searchForm.status = ''
  handleSearch()
}

// 详情
const handleDetail = (row) => {
  detail.value = { ...row, repaymentPlan: detail.value.repaymentPlan }
  detailVisible.value = true
}

// 还款
const handleRepayment = (row) => {
  currentLoan.value = row
  repaymentForm.amount = row.monthlyPayment
  repaymentForm.method = 'bank'
  repaymentForm.remark = ''
  repaymentVisible.value = true
}

// 提交还款
const handleRepaymentSubmit = async () => {
  if (!repaymentFormRef.value) return
  
  await repaymentFormRef.value.validate((valid, fields) => {
    if (valid) {
      // TODO: 实现还款提交逻辑
      ElMessage.success('还款提交成功')
      repaymentVisible.value = false
      handleSearch()
    }
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

// 格式化金额
const formatMoney = (value) => {
  return `¥ ${value.toFixed(2)}`
}

// 获取贷款类型文本
const getLoanTypeText = (type) => {
  const map = {
    personal: '个人消费贷',
    house: '住房贷款',
    car: '车辆贷款',
    business: '经营贷款'
  }
  return map[type]
}

// 获取还款方式文本
const getRepaymentMethodText = (method) => {
  const map = {
    equal: '等额本息',
    principal: '等额本金',
    interest: '先息后本'
  }
  return map[method]
}

// 获取状态类型
const getStatusType = (status) => {
  const map = {
    disbursed: 'warning',
    closed: 'success',
    overdue: 'danger'
  }
  return map[status]
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    disbursed: '已放款',
    closed: '已结清',
    overdue: '已逾期'
  }
  return map[status]
}

// 获取还款状态类型
const getRepaymentStatusType = (status) => {
  const map = {
    pending: 'info',
    paid: 'success',
    overdue: 'danger'
  }
  return map[status]
}

// 获取还款状态文本
const getRepaymentStatusText = (status) => {
  const map = {
    pending: '待还款',
    paid: '已还款',
    overdue: '已逾期'
  }
  return map[status]
}
</script>

<style scoped>
.loan-record {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.repayment-plan {
  margin-top: 20px;
}

.repayment-plan .title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style> 